use std::borrow::Cow;

use serde::Serialize;
use thiserror::Error;
use tokio::task::JoinError;


pub type IoErr = std::io::Error;

#[derive(Debug, Error)]
pub enum AppErr {

    #[error("io:{0}")]
    Io(#[from] IoErr),

    #[error("probe:{0}")]
    Probe(#[from] probe_rs::Error),

    #[error("{0}")]
    Custom(Cow<'static, str>),

    #[error("join:{0}")]
    Join(#[from] JoinError),
}


impl Serialize for AppErr {

    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: serde::Serializer {
        let msg = self.to_string();
        serializer.serialize_str(&msg)
    }
}

pub fn new_err(msg: &'static str) -> AppErr {
    AppErr::Custom(Cow::Borrowed(msg))
}

pub trait ErrWrap<T> {
    
    fn wrap(self) -> Result<T, AppErr>;
}

impl <T, E: std::error::Error> ErrWrap<T> for Result<T, E> {

    fn wrap(self) -> Result<T, AppErr> {
        match self {
            Ok(v) => Ok(v),
            Err(e) => Err(AppErr::Custom(Cow::Owned(e.to_string())))
        }
    }
}








